package com.datamation.swadeshi.view;


import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.listviewitems.ChartItem;
import com.datamation.swadeshi.listviewitems.LineChartItem;
import com.datamation.swadeshi.listviewitems.PieChartItem;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

 @SuppressLint("NewApi") 
 public class DashboardFragment extends Fragment  {
	
	 //dashboard variables
	 ListView lv_dashboard;
	 ChartDataAdapter cda;
	 ArrayList<ChartItem> list;
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		
        View rootView = inflater.inflate(R.layout.dash_board, container, false);
        setHasOptionsMenu(true);
        //actionBar = getActivity().getActionBar();
        //set title 
        createCutomActionBarTitle("Swadeshi Dashboard");
       
        //dashboard
        lv_dashboard = (ListView) rootView.findViewById(R.id.listView1);
        list = new ArrayList<ChartItem>();
       
        //line chart
        list.add(new LineChartItem(generateDataLine(1 + 1), getActivity().getApplicationContext()));
        //pie chart
        list.add(new PieChartItem(generateDataPie(2 + 1), getActivity().getApplicationContext()));
        
        cda = new ChartDataAdapter(getActivity().getApplicationContext(), list);
        //set dashboard
        lv_dashboard.setAdapter(cda);
       
        return rootView;
    }
	

	

	// Refresh menu item
    private MenuItem refreshMenuItem;
    
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.main, menu);
	    
	  }
//MenuItem refreshMenuItem = (MenuItem) menu.findItem(R.id.action_refresh).getActionView();
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
        case R.id.action_refresh:
            // refresh
            refreshMenuItem = item;
            // Refresh dashBoard 
            new RefreshData().execute();
            
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	
	/**
     * Async task to load the data from server
     * **/
    private class RefreshData extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            // set the progress bar view
            refreshMenuItem.setActionView(R.layout.action_progressbar);
 
            refreshMenuItem.expandActionView();
        }
 
        @Override
        protected String doInBackground(String... params) {
            // not making real request in this demo
            // for now we use a timer to wait for sometime
            try {
            	list.clear();
                //line chart
                list.add(new LineChartItem(generateDataLine(1 + 1), getActivity().getApplicationContext()));
                //pie chart
                list.add(new PieChartItem(generateDataPie(2 + 1), getActivity().getApplicationContext()));
                
                cda = new ChartDataAdapter(getActivity().getApplicationContext(), list);
            	
               Thread.sleep(500);
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }
 
        @Override
        protected void onPostExecute(String result) {
            refreshMenuItem.collapseActionView();
            lv_dashboard.clearTextFilter();
            //set dashboard
            lv_dashboard.setAdapter(cda);
            
            // remove the progress bar view
            refreshMenuItem.setActionView(null);
            
        }
    };
	 
	  
    private LineData generateDataLine(int cnt) {

        ArrayList<Entry> e1 = new ArrayList<Entry>();

        for (int i = 0; i < 12; i++)//month
        	{
            e1.add(new Entry((int) (Math.random() * 65) + 40, i));
        }

        LineDataSet d1 = new LineDataSet(e1, "New DataSet " + cnt + ", (1)");
        d1.setLineWidth(3f);
        d1.setCircleSize(5f);
        d1.setHighLightColor(Color.parseColor("#336699"));
        
        ArrayList<Entry> e2 = new ArrayList<Entry>();

        for (int i = 0; i < 12; i++) {
            e2.add(new Entry(e1.get(i).getVal() - 30, i));
        }

        LineDataSet d2 = new LineDataSet(e2, "New DataSet " + cnt + ", (2)");
        d2.setLineWidth(3f);
        d2.setCircleSize(5f);
        d2.setHighLightColor(Color.rgb(244, 117, 117));
        d2.setColor(ColorTemplate.VORDIPLOM_COLORS[0]);
        d2.setCircleColor(ColorTemplate.VORDIPLOM_COLORS[0]);
        
        ArrayList<LineDataSet> sets = new ArrayList<LineDataSet>();
        sets.add(d1);
        sets.add(d2);
        
        LineData cd = new LineData(getMonths(), sets);
        return cd;
    }
    
    private ArrayList<String> getMonths() {

        ArrayList<String> m = new ArrayList<String>();
        m.add("Jan");
        m.add("Feb");
        m.add("Mar");
        m.add("Apr");
        m.add("May");
        m.add("Jun");
        m.add("Jul");
        m.add("Aug");
        m.add("Sep");
        m.add("Okt");
        m.add("Nov");
        m.add("Dec");

        return m;
    }
    
    private class ChartDataAdapter extends ArrayAdapter<ChartItem> {
        
        public ChartDataAdapter(Context context, List<ChartItem> objects) {
            super(context, 0, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getItem(position).getView(position, convertView, getContext());
        }
        
        @Override
        public int getItemViewType(int position) {           
            // return the views type
            return getItem(position).getItemType();
        }
        
        @Override
        public int getViewTypeCount() {
            return 3; // we have 3 different item-types
        }
    }
    
    
    private PieData generateDataPie(int cnt) {

        ArrayList<Entry> entries = new ArrayList<Entry>();

        for (int i = 0; i < 4; i++) {
            entries.add(new Entry((int) (Math.random() * 70) + 30, i));
        }

        PieDataSet d = new PieDataSet(entries, "");
        
        // space between slices
        d.setSliceSpace(5f);
        d.setColors(ColorTemplate.PASTEL_COLORS);
        
        PieData cd = new PieData(getQuarters(), d);
        return cd;
    }
    
    private ArrayList<String> getQuarters() {
        
        ArrayList<String> q = new ArrayList<String>();
        q.add("1st Quarter");
        q.add("2nd Quarter");
        q.add("3rd Quarter");
        q.add("4th Quarter");
        
        return q;
    }

    //Title name method
    private void createCutomActionBarTitle(String title){
        
    	getActivity().getActionBar().setDisplayShowCustomEnabled(true);
    	getActivity().getActionBar().setDisplayShowTitleEnabled(false);

        LayoutInflater inflator = LayoutInflater.from(getActivity());
        View v = inflator.inflate(R.layout.custom_action_bar, null);

        //Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/fat_tats.ttf");
        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),"fonts/coopbl.ttf");
        
        TextView tvTitle = (TextView)v.findViewById(R.id.titleFragment1);
        tvTitle.setText(title);
        tvTitle.setTypeface(tf);
      
        //assign the view to the actionbar
        getActivity().getActionBar().setCustomView(v);
    }
}
